package log

import (
	"fmt"
	"os"
	"path/filepath"
	"runtime"

	"alolang.org.cn/api/server/config"
	"github.com/sirupsen/logrus"
)

var Logger *logrus.Logger

func LogInit() {
	if Logger != nil {
		panic("log.Logger is already initialized")
	}

	var logLevel logrus.Level
	switch config.Server.LogLevel {
	case "debug":
		logLevel = logrus.DebugLevel
	case "info":
		logLevel = logrus.InfoLevel
	default:
		panic("invalid log level: " + config.Server.LogLevel)
	}

	Logger = &logrus.Logger{
		Out:          os.Stdout,
		Level:        logLevel,
		Hooks:        make(logrus.LevelHooks),
		ExitFunc:     os.Exit,
		ReportCaller: true,
		Formatter: &logrus.TextFormatter{
			EnvironmentOverrideColors: false,
			ForceColors:               true,
			FullTimestamp:             true,
			TimestampFormat:           "2006-01-02 15:04:05.000",
			DisableSorting:            true,

			CallerPrettyfier: func(f *runtime.Frame) (function string, file string) {
				function = f.Function + ")"
				file = fmt.Sprintf("(%s:%d", filepath.Base(f.File), f.Line)
				return
			},
		},
	}
}
